package com.rm.wechatapp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rm.wechatapp.entity.AccountUser;
import com.rm.wechatapp.service.IAccountUserService;
import com.rm.wechatapp.service.IWeixinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xy
 * @Date: 2025/3/27 13:57
 */
@Slf4j
@RestController
@RequestMapping("/api/weixin")
public class AccountUserController {

    @Autowired
    private IWeixinService weixinService;

    @Autowired
    private IAccountUserService accountUserService;

    /**
     * 尝试登录
     */
    @GetMapping("/login/{code}")
    @ResponseBody
    public Map<String,Object> login(@PathVariable("code") String code) {
        System.out.println("测试接口1"+code);
        String openId = weixinService.getOpenId(code);
        QueryWrapper<AccountUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",openId);
        AccountUser accountUser = accountUserService.getOne(queryWrapper);
        Map<String,Object> result = new HashMap<>();
        if (accountUser != null) {
            result.put("isRegistered",true);
            result.put("name",accountUser.getName());
            result.put("avatar",accountUser.getAvatar());
        } else {
            result.put("isRegistered",false);
            result.put("name",null);
            result.put("avatar",null);
        }
        return result;
    }

    /**
     * 注册并保存用户信息
     */
    @PostMapping("/register")
    @ResponseBody
    public boolean register(@RequestBody Map<String,Object> requestBody) {
        System.out.println("测试接口2"+requestBody);
        String code = (String) requestBody.get("code");
        String openId = weixinService.getOpenId(code);
        AccountUser accountUser = new AccountUser();
        accountUser.setOpenId(openId);
        accountUser.setAvatar((String)requestBody.get("avatar"));
        accountUser.setName((String)requestBody.get("name"));
        accountUserService.save(accountUser);
        return true;
    }

}